package cn.school.demo.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.school.demo.pojo.Article
import cn.school.demo.pojo.Collect
import cn.school.demo.pojo.Result
import cn.school.demo.util.HttpApi
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.reflect.TypeToken
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class CollectRepository {
    private val httpApi: HttpApi

    init {
        val retrofit =
            Retrofit.Builder().baseUrl(DataRepository.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        httpApi = retrofit.create(HttpApi::class.java)
    }

    fun getCollectList(id: Int): LiveData<MutableList<Collect>> {
        val responseLiveData = MutableLiveData<MutableList<Collect>>()
        httpApi.getCollectList(mapOf("sfNumber" to id)).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    if (it.success) {
                        it.data["collect"]?.let { jsonData ->
                            try {
                                val list = GsonUtils.fromJson<MutableList<Collect>>(
                                    jsonData.toString(),
                                    object : TypeToken<MutableList<Collect>>() {}.type
                                )
                                list?.let {
                                    responseLiveData.value = list
                                } ?: LogUtils.e("出错了!!")
                                LogUtils.d(list)
                            } catch (e: Error) {
                                e.printStackTrace()
                            }
                        } ?: LogUtils.e("收藏列表http返回值的data为空!!")
                    } else {
                        responseLiveData.value = mutableListOf<Collect>()
                    }
                } ?: LogUtils.e("收藏列表http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }

    fun deleteCollectList(list: MutableList<Collect>): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        httpApi.deleteCollectList(mapOf("collect" to GsonUtils.toJson(list)))
            .enqueue(object : Callback<Result> {
                override fun onResponse(call: Call<Result>, response: Response<Result>) {
                    response.body()?.let {
                        responseLiveData.value = it
                    } ?: LogUtils.e("删除收藏http返回值为空！")
                }

                override fun onFailure(call: Call<Result>, t: Throwable) {
                    LogUtils.e(t)
                }
            })
        return responseLiveData
    }

    fun getArticleById(id: Int): LiveData<Article> {
        val responseLiveData = MutableLiveData<Article>()
        httpApi.getArticleByArticleId(mapOf("articleId" to id)).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    try {
                        val article = GsonUtils.fromJson<Article>(
                            it.data["article"].toString(),
                            object : TypeToken<Article>() {}.type
                        )
                        article?.let {
                            responseLiveData.value = article
                        } ?: LogUtils.e("article为空！！")
                    } catch (e: Error) {
                        e.printStackTrace()
                    }
                } ?: LogUtils.e("获取文章http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }

    fun saveCollectById(sfNumber: Int, articleId: Int, articleName: String): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        httpApi.saveCollectById(
            mapOf(
                "sfNumber" to sfNumber,
                "articleId" to articleId,
                "articleName" to articleName
            )
        ).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                response.body()?.let {
                    responseLiveData.value = it
                } ?: LogUtils.e("保存收藏http返回值为空！")
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }

        })
        return responseLiveData
    }

    fun cancelCollectById(sfNumber: Int, articleId: Int): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        httpApi.cancelCollectById(mapOf("sfNumber" to sfNumber, "articleId" to articleId))
            .enqueue(object : Callback<Result> {
                override fun onResponse(call: Call<Result>, response: Response<Result>) {
                    response.body()?.let {
                        responseLiveData.value = it
                    } ?: LogUtils.e("取消收藏http返回值为空！")
                }

                override fun onFailure(call: Call<Result>, t: Throwable) {
                    LogUtils.e(t)
                }

            })
        return responseLiveData
    }
}